package com.daniel.juc.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 详细说明
 *
 * @author Daniel
 * @version V1.0
 * @date 2020/5/25 11:27
 */
public class Demo01 {
	public static void main(String[] args) throws ExecutionException, InterruptedException {

		test2();
	}

	/**
	 * 没有返回值的 runAsync 异步回调
	 *
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	public static void test1() throws ExecutionException, InterruptedException {
		CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "runAsync->Void");
		});

		System.out.println("1111");

		completableFuture.get();

		System.out.println("2222");
	}

	/**
	 * 有返回值的 supplyAsync 异步回调
	 *
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	public static void test2() throws ExecutionException, InterruptedException {
		CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
			System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
			int i = 10 / 0;
			return 1024;
		});

		System.out.println(completableFuture.whenComplete((t, u) -> {
			System.out.println("t=>" + t);
			System.out.println("u=>" + u.getMessage());
		}).exceptionally((e) -> {
			System.out.println(e.getMessage());
			return 500;
		}).get());
	}

}
